import axios from 'axios'
import { Message } from 'element-ui'
import { sessionStorage } from './storage'
import router from '../../router'
import store from '../../vuex/store'

let baseURL = process.env.VUE_APP_BASE_URL || 'http://localhost:9001'

let request = axios.create({
  baseURL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})
request.interceptors.request.use(config => {
  let token = null
  try {
    token = sessionStorage.getItem('clientUserInfo').token
  } catch (error) {
    console.log(error)
  }
  config.headers.token = token
  // loading
  return config
}, error => {
  return Promise.reject(error)
})
request.interceptors.response.use(data => {
  if (+data.data.code === 401 || +data.data.code === 1011 || data.data.code === 150) {
    store.dispatch('setUserInfo', null)
    router.push('/home')
    Message({
      message: data.data.message || data.data.msg,
      center: true,
      type: 'error'
    })
  } else if (+data.data.code !== 1 && data.data.message) {
    Message({
      message: data.data.message,
      center: true,
      type: 'error'
    })
  } else if (data.data.code !== 0 && data.data.msg) {
    Message({
      message: data.data.msg,
      center: true,
      type: 'error'
    })
  }
  return data.data
}, error => {
  console.error(error)
  Message({
    message: '请求错误',
    center: true,
    type: 'error'
  })
  return Promise.reject(error)
})

export default {
  post (url, data) {
    return request.post(url, data)
  },
  put (url, data) {
    return request.put(url, data)
  },
  delete (url, data) {
    return request.delete(url, {
      params: data
    })
  },
  get (url, data, options) {
    return request.get(url, {
      params: data,
      ...options
    })
  }
}
